package org.lk.common.scheduler;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author: lk
 * @since:清理线程启动
 */
@Component
public class SchedulerThread {

    @Value("${flink.savepointDirectory:savepoints}")
    String savepointDirectory;

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    // 启动定时清理线程任务
    @PostConstruct
    public void startScheduler() {
        scheduler.scheduleAtFixedRate(() -> {
            // 开始清理文件
            File file = new File(savepointDirectory);
            deleteFolder(file);
        }, 0, 60 * 60 * 6, TimeUnit.SECONDS);
    }

    public void deleteFolder(File src) {
        File[] filearray = src.listFiles();
        if (filearray != null) {
            for (File i : filearray) {
                if (i.isDirectory()) {//判断他是否是文件还是文件夹
                    deleteFolder(i);//不是文件就让他在执行一轮这个方法
                } else {//如果是文件就直接删除
                    i.delete();
                }
            }
            src.delete();//删除空的文件夹

        }
    }
    // 程序关闭时关闭定时清理任务

    @PreDestroy
    public void stopSchedulerThread() {
        scheduler.shutdownNow();
    }


}
